defmodule SmartOneWeb.CarMoveController do
  use SmartOneWeb, :controller

  defmodule SmartOne.CarMoveController.SampleClient do
    use Hulaaki.Client

    def on_connect_ack(options) do
      IO.inspect options
    end

    def on_subscribed_publish(options) do
      IO.inspect options
    end

    def on_subscribe_ack(options) do
      IO.inspect options
    end

    def on_pong(options) do
      IO.inspect options
    end
  end

  @direction_map %{"unknown" => 0, "forward" => 1, "backward" => 2, "left" => 3, "right" => 4}

  def move(conn, %{"to" => direction}) do
    dir_code = Map.get(@direction_map, direction, 0)

    # msg_options = [id: 9_347, topic: "nope", message: Integer.to_string(dir_code), dup: 0, qos: 1, retain: 1]
    # SmartOne.MqttClient.publish_msg(msg_options)

    # notify_worker = Task.async(SmartOne.CarMoveController, :notify_move, [dir_code])
    # Task.await(notify_worker)
    notify_move(dir_code)

    pages = %{direction: direction, direction_code: dir_code}
    render conn, "move_to.json", pages: pages
  end

  def notify_move(dir_code) do
    {:ok, pid} = SmartOne.CarMoveController.SampleClient.start_link(%{parent: self()})
    conn_options = [client_id: "some-name", host: "127.0.0.1", port: 1883, timeout: 200]
    SmartOne.CarMoveController.SampleClient.connect(pid, conn_options)

    msg_options = [id: 9_347, topic: "nope", message: Integer.to_string(dir_code), dup: 0, qos: 1, retain: 1]
    SmartOne.CarMoveController.SampleClient.publish(pid, msg_options)

    SmartOne.CarMoveController.SampleClient.disconnect(pid)
    SmartOne.CarMoveController.SampleClient.stop(pid)
  end

end
